package com.design_patterns.flyweight;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-08-29 21:39
 **/

/**
 * 享元模式
 * 运用共享技术来有效地支持大量细粒度对象的复用。
 * 它通过共享已经存在的对象来大幅度减少需要创建的对象数量、避免大量相似类的开销，
 * 从而提高系统资源的利用率。
 */
public class Main {

    public static void main(String[] args) {
        new SourcePool();
        for (int i = 0; i < 500; i++) {
            new Thread(() -> {
                Source source = SourcePool.getSource();
                source.wake();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                source.kill();
            }).start();
        }
    }
}


class SourcePool {

    static List<Source> sourceList = new ArrayList<>();

    private static int defaultSize = 100;
    private static int maxSize = 500;
    private static int addSize = 0;

    public static int getSize() {
        return defaultSize + addSize;
    }

    //    初始化池
    static {
        for (int i = 0; i < defaultSize; i++) {
            Source source = new Source();
            sourceList.add(source);
        }
    }

    //    获取资源
    public synchronized static Source getSource() {
        int size = sourceList.size();
//        找可用资源
        for (int i = 0; i < size; i++) {
            Source source = sourceList.get(i);
            if (!source.live) {
                return source;
            }
        }

//        没到最大容量
        if (getSize() <= maxSize) {
            System.err.println("创建新对象我才会输出");
            ++addSize;
            Source source = new Source();
            sourceList.add(source);
            return new Source();
        } else {
            return getSource();
        }
    }
}

class Source {
    public boolean live = false;
    public int id;

    public void kill() {
        this.live = false;
    }

    public void wake() {
        this.live = true;
    }

    @Override
    public String toString() {
        return "Source{" +
                "live=" + live +
                ", id='" + id + '\'' +
                '}';
    }
}


